const app = getApp();
const db = wx.cloud.database().collection("crew")

Page({
  data: {
    name: '',
    opus: '',
    contact: '',
    location: '',
    imgUrl: '',
    tempImgUrl: '', // 用于保存暂存图片路径
    money: '',
    link: '',
    autosize: {
      maxHeight: 120,
      minHeight: 20,
    },
    priceError: false,
  },

  onPriceInput(e) {
    const { value } = e.detail;
    if (value !== '') { // 只有当输入不为空时才进行验证
      const isNumber = /^\d+(\.\d+)?$/.test(value);
      this.setData({
        priceError: !isNumber,
      });
    } else {
      this.setData({
        priceError: false, // 当输入为空时，不显示错误提示
      });
    }
  },

  handleUpload() {
    let that = this;
    wx.chooseImage({
      success: chooseResult => {
        const tempImgUrl = chooseResult.tempFilePaths[0];
        that.setData({
          tempImgUrl: tempImgUrl
        });
      },
    });
  },

  publishRent() {
    // Retrieve input values
    const { name, opus, contact, location, imgUrl, money, link, tempImgUrl } = this.data;

    // Check if required fields are filled
    if (!name  || !contact) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }

    // Check if money is a number
    if (!/^\d+(\.\d+)?$/.test(money)) {
      wx.showToast({
        title: '薪酬金额必须为数字',
        icon: 'error'
      });
      return;
    }

    // 如果有暂存的图片路径，则先上传图片到云存储
    if (tempImgUrl) {
      wx.showLoading({
        title: '上传中',
      });
      wx.cloud.uploadFile({
        cloudPath: 'crew/' + (new Date()).valueOf() + '.png',
        filePath: tempImgUrl,
        success: res => {
          console.log('上传成功', res);
          const imgUrl = res.fileID;
          this.setData({
            imgUrl: imgUrl,
            tempImgUrl: '' // 清空暂存图片路径
          });
          this.addCrewToDatabase();
        },
        fail: err => {
          console.error('上传失败', err);
          wx.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    } else {
      this.addCrewToDatabase();
    }
  },

  addCrewToDatabase() {
    // Retrieve input values
    const { name, opus, contact, location, imgUrl, money, link } = this.data;

    db.add({
      data: {
        name: name,
        opus: opus,
        contact: contact,
        location: location,
        picture_url: imgUrl,
        classify: this.data.type,
        money: money,
        link: link
      }
    }).then(res => {
      console.log('数据添加成功', res);
      this.setData({
        name: '',
        opus: '',
        contact: '',
        location: '',
        money: '',
        link: ''
      });
      wx.showToast({
        title: '发布成功',
        icon: 'success'
      });
    }).catch(err => {
      // Error handling
      console.error('数据添加失败', err);
      wx.showToast({
        title: '发布失败，请重试',
        icon: 'none'
      });
    });
  },

  onLoad: function(options) {
    if (options.type) {
      this.setData({
        type: options.type
      });
    }
    console.log("this.data.type:", this.data.type); // Check the value of this.data.type
  },

  onUnload: function() {
    const pages = getCurrentPages();
    if (pages.length >= 2) {
      const prevPage = pages[pages.length - 2];
      if (prevPage.getCrewData) {
        prevPage.getCrewData();
      }
    }
  }
});
